﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

namespace Web_Blog.Controler
{
    public class POST
    {
        //Gửi bài viết
        public static int Send(Object.SendPostObject post)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procGuiBai", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@uID", post.Uid));
            command.Parameters.Add(new SqlParameter("@title", post.Title));
            command.Parameters.Add(new SqlParameter("@content", post.Contents));

            SqlParameter retval = new SqlParameter("@Ret", SqlDbType.Int);
            retval.Direction = ParameterDirection.ReturnValue;
            command.Parameters.Add(retval);

            command.ExecuteNonQuery();
            int retvalue = int.Parse(command.Parameters["@Ret"].Value.ToString());
            conn.Close();

            return retvalue;
        }

        //Lấy 1 bài viết =======================================================================
        public static Object.Load1PostObject Load(int pID)
        {
            Object.Load1PostObject post = new Object.Load1PostObject();

            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procLay1BaiViet", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@pID", pID));

            SqlDataReader reader = null;

            reader = command.ExecuteReader();

            if (reader.Read())
            {
                post.Nick = reader["nick"].ToString();
                post.Avatar = reader["avatar"].ToString() != "" ? reader["avatar"].ToString() : "";
                post.Createdate = reader["createdate"].ToString();
                post.Modifydate = reader["modifydate"].ToString()!="" ? reader["modifydate"].ToString() : "";
                post.UID = int.Parse(reader["userID"].ToString());
                post.Title = reader["title"].ToString();
                post.Contents = reader["contents"].ToString();
                post.Liked = reader["liked"].ToString() != "" ? reader["liked"].ToString() : "";
                post.Name = reader["name"].ToString();
                post.Tag = reader["tag"].ToString() != "" ? reader["tag"].ToString() : "";
                post.PID = int.Parse(reader["pID"].ToString());
                post.Block = int.Parse(reader["block"].ToString() != "" ? reader["block"].ToString() :"0");
            }
            conn.Close();

            return post;
        }

        //Sửa 1 bài viết
        public static int Update(Object.SendPostObject post)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procSua1BaiViet", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@pID", post.Uid));
            command.Parameters.Add(new SqlParameter("@title", post.Title));
            command.Parameters.Add(new SqlParameter("@contents", post.Contents));

            int retval = command.ExecuteNonQuery();

            conn.Close();

            return retval;
        }

        //Lấy danh sách các bài viết
        public static string LoadPostList(int uID, int uIDflag)
        {
            string dsbaiviet = "";

            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procLayDanhSachBaiViet", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@uID", uID));

            SqlDataReader reader = null;

            reader = command.ExecuteReader();
            while (reader.Read())
            {
                dsbaiviet += "<a href='BaiViet.aspx?p=" + reader["pID"].ToString();      //Nơi dẫn link đến bài viết

                if (uIDflag != -1)
                    dsbaiviet += "&u=" + uIDflag;
                dsbaiviet += "'>";

                dsbaiviet += "<h1>" + reader["title"].ToString() + "</h1><br/>";
                dsbaiviet += "</a>";

                string preview = Controler.Other.StripTagsCharArray(reader["contents"].ToString());
                dsbaiviet += preview.Length < 400 ? preview : preview.Substring(0, 400);

                dsbaiviet += "<br/>Ngày tạo: " + reader["createdate"].ToString() + " | ";
                string liked = reader["liked"].ToString();
                if (liked != null)
                    dsbaiviet += "Liked: " + liked.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Length + "<br/>";

                dsbaiviet += "<br/><br/><br/>";                         //Phân cách giữa các bài viết
            }
            conn.Close();
            return dsbaiviet;
        }

        //Lấy top post
        public static string LoadTopPost()
        {
            string retval = "";
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procLayTopPost", conn);
            command.CommandType = CommandType.StoredProcedure;

            SqlDataReader reader = null;

            reader = command.ExecuteReader();

            while (reader.Read())
            {
                retval += "<li><span class=\"comment\"><a href=\"";
                retval += "BaiViet.aspx?p=" + reader["postID"].ToString();
                retval += "\">";
                retval += "(" + reader["dem"].ToString() + ") ";
                retval += reader["title"].ToString().Length > 30 ? reader["title"].ToString().Substring(0, 30) + "..." : reader["title"].ToString();
                retval += "</a></span><br />";
                retval += "<a href=\"TrangChu.aspx?u=" + reader["uID"].ToString() + "\">" + reader["nick"].ToString() + "</a>";
                retval += "</li>";
            }
            conn.Close();

            return retval;
        }

        //Xóa bài viết
        public static void Delete(int pID)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procXoaPost", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@pID", pID));

            command.ExecuteNonQuery();

            conn.Close();
        }

        //Search bài viết
        public static string SearchPost(string keyword)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            string dsbaiviet = "";

            SqlCommand command = new SqlCommand("procTimBaiViet", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@key", keyword));

            SqlDataReader reader = null;

            reader = command.ExecuteReader();
            while (reader.Read())
            {
                dsbaiviet += "<a href='BaiViet.aspx?p=" + reader["pID"].ToString();      //Nơi dẫn link đến bài 
                dsbaiviet += "'>";

                dsbaiviet += "<h1>" + reader["title"].ToString() + "</h1><br/>";
                dsbaiviet += "</a>";

                string preview = Controler.Other.StripTagsCharArray(reader["contents"].ToString());
                dsbaiviet += preview.Length < 400 ? preview : preview.Substring(0, 400);

                dsbaiviet += "<br/>Ngày tạo: " + reader["createdate"].ToString() + " | ";
                string liked = reader["liked"].ToString();
                if (liked != null)
                    dsbaiviet += "Liked: " + liked.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Length + "<br/>";

                dsbaiviet += "<br/><br/><br/>";                         //Phân cách giữa các bài viết
            }
            conn.Close();
            return dsbaiviet;
        }

        //================================Dành cho admin

        //Search bài viết admin
        public static string SearchPostAdmin(string keyword, string user)
        {
            string userIDsearch = "";
            if (user != "")
                userIDsearch = Controler.Account.SearchUserIDAdmin(user);


            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            string dsbaiviet = "";

            SqlCommand command = new SqlCommand("procTimBaiViet", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@key", keyword));

            SqlDataReader reader = null;

            reader = command.ExecuteReader();

            dsbaiviet += "<tr>";
            dsbaiviet += "<td>Post ID</td>";
            dsbaiviet += "<td>Người viết</td>";
            dsbaiviet += "<td>Tiêu đề</td>";
            dsbaiviet += "<td>Ngày viết</td>";
            dsbaiviet += "<td>Trạng thái</td>";
            dsbaiviet += "<td>Xóa</td>";
            dsbaiviet += "</tr>";

            while (reader.Read())
            {
                //Kiểm tra coi có đúng điều kiện user không
                if (user != "")
                {
                    string temp = ";" + reader["userID"].ToString() + ";";
                    if (!userIDsearch.Contains(temp)) continue;
                }

                dsbaiviet += "<tr>";

                dsbaiviet += "<td>" + reader["pID"].ToString() + "</td>";
                dsbaiviet += "<td>" + Controler.Account.LoadProfile(int.Parse(reader["userID"].ToString())).Nick + "</td>";
                dsbaiviet += "<td><a target=\"_blank\" href=\"../BaiViet.aspx?p=" + reader["pID"].ToString() + "\">" + reader["title"].ToString() + "</a></td>";
                dsbaiviet += "<td>" + reader["createdate"].ToString() + "</td>";
                dsbaiviet += "<td><a href=\"./Khoa.aspx?p=" + reader["pID"].ToString() + "\">" + (reader["block"].ToString() == "1" ? "Khóa" : "Mở") + "</a></td>";
                dsbaiviet += "<td><a href=\"./Xoa.aspx?p=" + reader["pID"].ToString() + "\">Xóa</a></td>";
                dsbaiviet += "</tr>";
            }
            conn.Close();
            return dsbaiviet;
        }

        //Hàm khóa, mở khóa bài viết
        public static int BlockPost(int pID, int block)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procBlockBaiViet", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@pID", pID));
            command.Parameters.Add(new SqlParameter("@bloc", block));
            int retval = command.ExecuteNonQuery();

            conn.Close();

            return retval;
        }
    }
}
